<template>
  <div class="container">

    code
    <van-uploader v-model="fileList"  :after-read="afterRead" :max-count='1' />
    <!-- <van-uploader :after-read="afterRead" /> -->

    <!-- <span @click="chooseImage">上传</span>
    <img :src="uploadImgUrl" alt="" class="upload_img"> -->


  </div>
</template>

<script>
// import { location } from "../assets/js/location";
const wx = require('weixin-js-sdk');

export default {
  name: 'home',
  data() {
    return {
      fileList: [],
      uploadImgUrl: '',
      
    }
  },
  created() {
   
    this.questionnaireType = this.$route.query.type;
    this.questionModel = this.$route.query.model;
    

    // 跳转获取微信 openId
    // this.initWxOpenId();

    
   
    // this.getSchoolList();

    // 微信相关
    this.initWxConfig();

    
    // this.getQuestion(this.questionnaireType);


  },
  mounted() {
  },
  watch: {
    
  },
  methods: {
   
    initWxOpenId() {
      let url = window.location.href;
      url = encodeURIComponent(url)
      // console.log(url)
      let code = this.getUrlParam('code')
      if(!code) {
        window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6461e3736f9366e9&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`)
      } else {
        this.wxCode = code;
        this.$axios.get(`http://39.105.125.149:8060/banma/getOpenId?code=${this.wxCode}`)
        .then(res => {
          console.log(res.data)   // openId
          this.openId = res.data.data;
        }).catch(res => {
          
        })
      }

      console.log(this.wxCode);

    },

    initAccessToken() {
      // this.$axios.get

      // https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx6461e3736f9366e9&secret=SECRET&code=CODE&grant_type=authorization_code
    },

    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file.content);
      console.log(file);
    },

    

    
    // 获取校区
    getSchoolList() {
      this.$axios.get(`http://39.105.125.149:8060/banma/querySchoolList?schoolId=`).then(res => {
        this.schoolList = res.data.data;
        this.schoolList.forEach(item => {
          this.slots[0].values.push(item.schoolName)
        })

        let str = '校区选择'
        this.slots[0].values.unshift(str)


      }).catch(err => {

      })
    },

    onValuesChange(picker, values) {
      this.schoolName = values[0];
      this.schoolList.forEach(item => {
        if(item.schoolName == values[0]) {
          this.schoolId = item.schoolId
          if(item.latitude) {
            this.targetPosition = {
              lat: item.latitude,
              lng: item.longitude,
            }
          }
          
        }
      })

      this.getDistance();     // 选择校区后 计算距离
      
      console.log(this.distance + '米')
      console.log('aaaaaaaaaa')
      console.log(this.maxDistance + '米')
      // alert(this.distance + '米')

      
      if(this.questionnaireType == 'midTerm') {
        this.$axios.get('http://39.105.125.149:8060/banma/queryClassBySchoolId', {
          params: {
            schoolId: this.schoolId
          }
        }).then(res => {
          this.classList = []
          this.slotsClass[0].values = []
          this.classList = res.data.data;
          this.classList.forEach(item => {
            this.slotsClass[0].values.push(item.className)
          })

          let str = '班级选择'
          this.slotsClass[0].values.unshift(str)
        }).catch(err => {

        })
      }
    },

    onValuesChangeClass(picker, values) {
      this.className = values[0];
      this.classList.forEach(item => {
        if(item.className == values[0]) {
          this.classId = item.classId
        }
      })
    },
    


    initWxConfig() {
      let _this = this;
      let url = window.location.href.split('#')[0];
      url = encodeURIComponent(url)
      console.log(url);
      this.$axios.get(`http://39.105.125.149:8060/banma/getTimestampNonceStrSignature?url=${url}`)
      .then(res => {
        res = res.data.data
        // console.log(res)
        wx.config({
          debug: false, // 开启调试模式,
          appId: 'wx6461e3736f9366e9', // 必填，企业号的唯一标识，此处填写企业号corpid
          timestamp: res.timestamp, // 必填，生成签名的时间戳
          nonceStr: res.nonceStr, // 必填，生成签名的随机串
          signature: res.signature,// 必填，签名，见附录1
          // jsApiList: ['openlocation', 'getLocation',] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
          jsApiList: ['chooseImage','uploadImage','getLocalImgData','downloadImage'],
        });

        wx.ready(function(){
          // 在这里调用 API
          wx.checkJsApi({
            jsApiList: [
              'chooseImage',
              'uploadImage',
              'getLocalImgData',
              'downloadImage'
            ],
            success: function (res) {
              console.log(JSON.stringify(res));
            }
          });
          /** 
          wx.getLocation({
            type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {
              // alert(res.latitude)
              // console.log(res)
              _this.userPosition = {
                lat: res.latitude,
                lng: res.longitude,
              }
              _this.getDistance();

            // var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            // var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
            // var speed = res.speed; // 速度，以米/每秒计
            var accuracy = res.accuracy; // 位置精度

            },
            error(err) {
              // console.log(err);
            }
          });*/
        })

        wx.error(function(err){
          console.log(err)
        })


      }).catch(err => {
        
      })
    },

    chooseImage() {
      let _this = this;
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 能够指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 能够指定来源是相冊还是相机，默认二者都有
        success: function (res) {
          let localIds = res.localIds[0]; // 返回选定照片的本地ID列表，localId能够作为img标签的src属性显示图片
          
          console.log(localIds);
          _this.uploadImage(localIds);
          _this.getLocalImgData(localIds)
        }
      });
    },

    uploadImage(localIds) {
      wx.uploadImage({
        localId: localIds, // 需要上传的图片的本地ID，由chooseImage接口获得
        isShowProgressTips: 1, // 默认为1，显示进度提示
        success: function (res) {
          let serverId = res.serverId; // 返回图片的服务器端ID
          console.log('serverId: ' + serverId)
        }
      });
    },
    getLocalImgData(localIds) {
      let _this = this;
      wx.getLocalImgData({
        localId: localIds, // 图片的localID
        success: function (res) {
          let localData = res.localData; // localData是图片的base64数据，可以用img标签显示
          _this.uploadImgUrl = localData;
          console.log("imgUrl: " + localData)
        }
      });
    },

    // is_weixin(){
    //   var ua = navigator.userAgent.toLowerCase(); //判断浏览器的类型
    //   if(ua.match(/MicroMessenger/i)=="micromessenger") {
    //       return true;
    //   } else {
    //       return false;
    //   }
    // },

    getUrlParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    
    inputBlur() {
      window.scrollTo(0, document.documentElement.clientHeight); 
    }
  },
  computed: {
    

  },
}
</script>


<style scoped>
.input {
  width: 100px;
  height: 100px;
  background: #000;
  display: inline-block;
}

.upload_img {
  width: 100px;
  height: 100px;
  display: inline-block;
}
</style>